package com.caizi.algorithm;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 
 *@Title:
 *@Description:获取质数
 *@Author:caizi
 *@Since:2011-4-19
 *@Version:1.1.0
 */
public class PrimeNumber implements Runnable {
    int num = 0;

    public PrimeNumber(int num) {
        this.num = num;
    }

    public static void main(String... args) {
        long startTime = System.currentTimeMillis();
        System.out.println("Strat Time is [" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(startTime)) + "].");
        for (int i = 0; i < 5; i++) {
            Runnable runnable = new PrimeNumber(10000 * (i + 1));
            Thread thread = new Thread(runnable);
            thread.start();
        }
        long endTime = System.currentTimeMillis();
        System.out.println("End Time is [" + new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS").format(new Date(endTime)) + "].");
        System.out.println("Run Time is [" + (endTime - startTime) / 1000.0 + "s].");
    }

    public void getPrimeNumber() {
        List<Integer> list = new ArrayList<Integer>();
        for (int i = 2; i <= num; i++) {
            boolean bool = true;
            for (int j = 2; j * j < i + 1; j++) {
                // 当一个整数除了能被1和自己整除外，不能被其他整数整除，称为质数
                if (i % j == 0) {
                    bool = false;
                    break;
                }
            }
            if (bool) {
                list.add(i);
            }
        }
        System.out.println("Thread " + Thread.currentThread().getId() + " get Prime Number is " + list);
    }

    public void run() {
        getPrimeNumber();
    }
}
